// 博客栏目管理API服务
const express = require('express');
const BlogColumn = require('../models/BlogColumn');
const { authenticateToken, Authorization } = require('../security');
const { USER_ROLES } = require('../security');
const { cacheMiddleware, clearCache } = require('../cache');

const router = express.Router();

// 获取所有栏目
router.get('/blog-columns', cacheMiddleware(300), async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 100;
        
        const result = await BlogColumn.findAll({ page, limit });
        
        res.json({
            success: true,
            data: {
                columns: result.columns,
                total: result.total,
                page: page,
                limit: limit,
                totalPages: result.totalPages
            }
        });
    } catch (error) {
        console.error('获取栏目列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取栏目列表失败'
        });
    }
});

// 获取单个栏目
router.get('/blog-columns/:id', cacheMiddleware(600), async (req, res) => {
    try {
        const column = await BlogColumn.findById(parseInt(req.params.id));
        
        if (!column) {
            return res.status(404).json({
                success: false,
                message: '栏目不存在'
            });
        }
        
        res.json({
            success: true,
            data: column
        });
    } catch (error) {
        console.error('获取栏目失败:', error);
        res.status(500).json({
            success: false,
            message: '获取栏目失败'
        });
    }
});

// 创建栏目
router.post('/blog-columns', authenticateToken, Authorization.requirePermission('blog_columns', 'create'), async (req, res) => {
    try {
        const { name, slug, description, categories = [], sortOrder } = req.body;
        
        if (!name) {
            return res.status(400).json({
                success: false,
                message: '栏目名称不能为空'
            });
        }
        
        // 检查栏目名称是否已存在
        const existingColumns = await BlogColumn.findAll();
        const nameExists = existingColumns.columns.some(col => col.name === name);
        
        if (nameExists) {
            return res.status(400).json({
                success: false,
                message: '栏目名称已存在'
            });
        }
        
        const column = await BlogColumn.create({
            name,
            slug,
            description,
            categories,
            sortOrder
        });
        
        // 清除缓存
        clearCache('/api/blog-columns');
        
        res.status(201).json({
            success: true,
            message: '栏目创建成功',
            data: column
        });
    } catch (error) {
        console.error('创建栏目失败:', error);
        res.status(500).json({
            success: false,
            message: '创建栏目失败'
        });
    }
});

// 更新栏目
router.put('/blog-columns/:id', authenticateToken, Authorization.requirePermission('blog_columns', 'update'), async (req, res) => {
    try {
        const column = await BlogColumn.findById(parseInt(req.params.id));
        
        if (!column) {
            return res.status(404).json({
                success: false,
                message: '栏目不存在'
            });
        }
        
        // 检查栏目名称是否已存在（排除当前栏目）
        if (req.body.name) {
            const existingColumns = await BlogColumn.findAll();
            const nameExists = existingColumns.columns.some(
                col => col.name === req.body.name && col.id !== column.id
            );
            
            if (nameExists) {
                return res.status(400).json({
                    success: false,
                    message: '栏目名称已存在'
                });
            }
        }
        
        await BlogColumn.update(column.id, req.body);
        
        // 清除缓存
        clearCache('/api/blog-columns');
        clearCache(`/api/blog-columns/${column.id}`);
        
        res.json({
            success: true,
            message: '栏目更新成功',
            data: column
        });
    } catch (error) {
        console.error('更新栏目失败:', error);
        res.status(500).json({
            success: false,
            message: '更新栏目失败'
        });
    }
});

// 删除栏目
router.delete('/blog-columns/:id', authenticateToken, Authorization.requirePermission('blog_columns', 'delete'), async (req, res) => {
    try {
        const column = await BlogColumn.findById(parseInt(req.params.id));
        
        if (!column) {
            return res.status(404).json({
                success: false,
                message: '栏目不存在'
            });
        }
        
        await BlogColumn.delete(column.id);
        
        // 清除缓存
        clearCache('/api/blog-columns');
        clearCache(`/api/blog-columns/${column.id}`);
        
        res.json({
            success: true,
            message: '栏目删除成功'
        });
    } catch (error) {
        console.error('删除栏目失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '删除栏目失败'
        });
    }
});

// 获取栏目统计
router.get('/blog-columns/:id/stats', cacheMiddleware(300), async (req, res) => {
    try {
        const columnId = parseInt(req.params.id);
        const column = await BlogColumn.findById(columnId);
        
        if (!column) {
            return res.status(404).json({
                success: false,
                message: '栏目不存在'
            });
        }
        
        const stats = await BlogColumn.getStats(columnId);
        
        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取栏目统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取栏目统计失败'
        });
    }
});

// 根据分类获取栏目
router.get('/blog-columns/by-category/:categoryId', cacheMiddleware(300), async (req, res) => {
    try {
        const categoryId = parseInt(req.params.categoryId);
        const columns = await BlogColumn.findByCategory(categoryId);
        
        res.json({
            success: true,
            data: columns
        });
    } catch (error) {
        console.error('根据分类获取栏目失败:', error);
        res.status(500).json({
            success: false,
            message: '根据分类获取栏目失败'
        });
    }
});

module.exports = router;